package com.yingpai.fitness.dvp_2_0.main.activity;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;

import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.yingpai.fitness.R;
import com.yingpai.fitness.base.BaseResponse;
import com.yingpai.fitness.dvp_2_0.common.activity.CommonActivity;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.callback.Callback;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.request.RequestType;
import com.yingpai.fitness.dvp_2_0.common.util.ContextUtil;
import com.yingpai.fitness.dvp_2_0.common.util.constant.Contacts;
import com.yingpai.fitness.dvp_2_0.main.util.constant.Constant;
import com.yingpai.fitness.dvp_2_0.main.util.constant.Url;
import com.yingpai.fitness.entity.register.RegisterBean;
import com.yingpai.fitness.dvp_2_0.main.util.XCountDownTimer;
import com.yingpai.fitness.dvp_2_0.main.util.NetWorkUtil;
import com.yingpai.fitness.dvp_2_0.main.util.encrypt.RsaEncrypt;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by ASUS on 2018/11/6.
 */

public class ForgetPassWordActivity extends CommonActivity implements TextWatcher {
    @BindView(R.id.forgetPhoneEt)
    EditText forgetPhoneEt;
    @BindView(R.id.forgetPasswordEt)
    EditText forgetPasswordEt;
    @BindView(R.id.forget_verification_Et)
    EditText forgetVerificationEt;
    @BindView(R.id.verification_code_tv)
    TextView verificationCodeTv;
    private String phoneNum;
    private XCountDownTimer timer;
    private String vercodeStr;
    private String passwordStr;
    private String beforeWord;
    private String specialWords = "-/:;()$&@\"_'`*#%[]{}!^￥+.,\\<>?~";//特殊字符专用串

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 隐藏状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_forgetpassword_layout);
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initData() {

    }

    @OnClick({R.id.forget_back_iv, R.id.verification_code_tv, R.id.forgeOkBtn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.forget_back_iv:
                finishActivity();
                break;
            case R.id.verification_code_tv:
                getVerCode();
                break;
            case R.id.forgeOkBtn:
                //确认修改按钮
                if (checkInfoComplete()) {
                    modifyPassword();
                }
                break;
            case R.id.to_login:
                startActivity(LoginActivity.class);
                break;
        }
    }

    private void modifyPassword() {
        showDialog(this, "修改密码...");
        String phoneNumsSec = "";
        String passwordSec = "";
        try {
            //加密
            phoneNumsSec = RsaEncrypt.getInstance(ContextUtil.getContext()).encryptWithBase64(phoneNum);
            passwordSec = RsaEncrypt.getInstance(ContextUtil.getContext()).encryptWithBase64(passwordStr);
        } catch (Exception e) {
            e.printStackTrace();
        }

        HttpParams httpParams = new HttpParams();
        httpParams.put("phoneNo", phoneNumsSec);
        httpParams.put("password", passwordSec);
        httpParams.put("identifier", vercodeStr);
        finalOkGo.request(RequestType.POST, Contacts.HOST_SERVER + Url.MODIFY_PASSWORD, httpParams, Url.MODIFY_PASSWORD, new Callback<RegisterBean>() {
            @Override
            public void onSuccess(RegisterBean registerBean) {
                dismissDialog();
                if (Constant.REQUEST_SUCCESS.equals(registerBean.getResult())) {
                    EventBus.getDefault().postSticky("login," + phoneNum + "," + passwordStr);
                    finishActivity();
                } else {
                    showToast(registerBean.getMsg());
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                dismissDialog();
            }
        });
    }

    /**
     * 非空判断
     *
     * @return true：可以进行下一步  false：还有非法项
     */
    private boolean checkInfoComplete() {
        phoneNum = forgetPhoneEt.getText().toString().trim();
        if (!TextUtils.isEmpty(phoneNum)) {
            //手机号不为空，进行下一步判断
            if (phoneNum.length() == 11) {
                //手机号长度正确，进行下一步判断
                vercodeStr = forgetVerificationEt.getText().toString().trim();
                if (!TextUtils.isEmpty(vercodeStr)) {
                    //验证码正确，进行下一步判断
                    passwordStr = forgetPasswordEt.getText().toString().trim();
                    if (!TextUtils.isEmpty(passwordStr)) {
                        //密码有东西
                        if (passwordStr.length() >= 6) {
                            //密码符合长度

                        } else {
                            //密码太短
                            showToast("请输入6-12位密码");
                            forgetPasswordEt.requestFocus();
                            return false;
                        }
                    } else {
                        //密码为空
                        showToast("请输入密码");
                        forgetPasswordEt.requestFocus();
                        return false;
                    }
                } else {
                    //验证码为空
                    showToast("请填写验证码");
                    forgetVerificationEt.requestFocus();
                    return false;
                }
            } else {
                //手机号长度错误
                showToast("请输入正确的手机号码");
                forgetPhoneEt.requestFocus();
                return false;
            }
        } else {
            //手机号为空
            showToast("请输入手机号码");
            forgetPhoneEt.requestFocus();
            return false;
        }
        return true;
    }

    private void getVerCode() {
        showDialog(this, "获取中...");
        //先获取到填写的手机号
        phoneNum = forgetPhoneEt.getText().toString().trim();
        if (TextUtils.isEmpty(phoneNum)) {
            //电话号是空的，吐司提示
            showToast("请填写手机号");
            forgetPhoneEt.requestFocus();
        } else {
            if (NetWorkUtil.isConnected() && NetWorkUtil.isAvailableByPing()) {
                String mPhoneNumber = "";
                try {
                    mPhoneNumber = RsaEncrypt.getInstance(ContextUtil.getContext()).encryptWithBase64(phoneNum);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                HttpParams httpParams = new HttpParams();
                httpParams.put("phoneNo", mPhoneNumber);
                finalOkGo.request(RequestType.POST, Contacts.HOST_SERVER + Url.GET_FORGET_PASSWORD_VERCODE, httpParams, Url.GET_FORGET_PASSWORD_VERCODE, new Callback<BaseResponse>() {
                    @Override
                    public void onSuccess(BaseResponse baseResponse) {
                        dismissDialog();
                        if (Constant.REQUEST_SUCCESS.equals(baseResponse.getResult())) {
                            timer = new XCountDownTimer(6 * 10000, 1000, verificationCodeTv, 1);
                            timer.start();
                            showToast(baseResponse.getMsg());
                        } else {
                            showToast(baseResponse.getMsg());
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        dismissDialog();
                        //showToast("发送超时");
                    }
                });
            } else {
                showToast("网络不可用，请检查网络设置");
            }
        }
    }


    /**
     * 编辑框文本改变之前
     *
     * @param s
     * @param start
     * @param count
     * @param after
     */
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        beforeWord = s.toString();
    }

    /**
     * 文本改变中
     *
     * @param s
     * @param start
     * @param before
     * @param count
     */
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
    }

    /**
     * 文本改变后
     *
     * @param s
     */
    @Override
    public void afterTextChanged(Editable s) {
        if (s.toString().equals(beforeWord)) {
            return;
        }
        if (!TextUtils.isEmpty(s.toString())) {
            for (int i = 0; i < s.toString().length(); i++) {
                if (specialWords.contains(s.toString().charAt(i) + "")) {
                    //发现了特殊字符，还原成之前的样子
                    forgetPasswordEt.setText(beforeWord);
                    forgetPasswordEt.setSelection(forgetPasswordEt.getText().toString().length());
                    return;
                }
            }
        }
    }
}
